package com.starblink.post.detail.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Error
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.commContext
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.network.config.PostConfig.postRecommendPage
import com.starblink.android.basic.util.ImageUtils
import com.starblink.rocketreserver.FetchPostsQuery
import com.starblink.rocketreserver.QueryContentDetailQuery
import com.starblink.rocketreserver.SharePostMutation
import com.starblink.rocketreserver.fragment.PostD
import com.starblink.rocketreserver.type.PostRecommendQueryParam
import kotlinx.coroutines.launch

class SinglePostDetailVM : BaseViewModel() {
    var mList: MutableLiveData<ArrayList<PostD>> = MutableLiveData()
    var loadDetail = false

    /**
     * 获取内容详情
     */
    fun getPostDetail(postId: String) {
        if (!loadDetail) {
            loadDetail = true
            viewModelScope.launch {
                val response = SkGqlClient.skQuery(
                    QueryContentDetailQuery(postId),
                    showErrorToast = false,
                    showFailToast = false
                )

                if (response?.data != null && response.data!!.queryContentDetail != null && response.data!!.queryContentDetail!!.postD != null) {
                    var post = response.data!!.queryContentDetail!!.postD
//                Log.e("SinglePostDetailVM","=====${post.productList}")
                    if (mList.value?.isNotEmpty() == true) {
                        if (mList.value!!.first().id == postId) {
                            mList.value?.set(0, post)
                        } else {
                            mList.value?.add(0, post)
                        }
                        mList.value = mList.value
                    } else {
                        mList.value = arrayListOf(post)
                    }
                } else {
                    mList.value = arrayListOf()
                    var msg = ""
                    val errors = response?.errors
                    if (errors != null && errors.isNotEmpty()) {
                        var error: Error = response.errors!!.first()
                        msg = error.message
                    }
                    loadError(msg)

                }
            }
        }
    }

    /**
     * 获取相关推荐列表
     */
    fun getRecommend(postId: String) {
        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                FetchPostsQuery(
                    postParams = PostRecommendQueryParam(
                        3,
                        relatedPostId = Optional.present(postId),
                        postRecommendPage,
                        12,
                        advertiseId = if (AppsflyerManager.getADID().isNotEmpty()) Optional.present(
                            AppsflyerManager.getADID()
                        ) else Optional.absent(),
                        clientTime = Optional.present(System.currentTimeMillis().toString()),
                        isReported = Optional.present(true),
                    ), isPostDetail = true
                )

            )

            if (response?.data != null && response.data!!.fetchRecommendPost != null) {
                var postList = response.data!!.fetchRecommendPost
                var list = arrayListOf<PostD>()
                postList!!.forEach { e ->
                    e.postD?.let { list.add(it) }
                    var imgUrl = e.postD?.mainPic
                    ImageUtils.preloadImage(commContext(), imgUrl)
                }
                postRecommendPage++
                if (mList.value == null) {
                    mList.value = arrayListOf()
                }
//                Log.e("SinglePostDetailVM","====$postId====${list}")
                mList.value?.addAll(list)
                mList.value = mList.value
            }
        }
    }

    fun sharePost(postId: String) {
        viewModelScope.launch {
            val response = SkGqlClient.skMutation(
                SharePostMutation(postId)
            )
        }
    }

}